<?php
class new_smsServiceDriver extends smsServiceDriver
{
	private $cfg = array();
	private $Gateway = "http://api.sms.cn/mt/";
	public function config($cfg)
	{
		$this->cfg = $cfg;
	}
	
	public function IMSend($phone,$content)
	{
		if (false != $exids = $this->BC_EXPS($phone,$content,$this->cfg['bcmax']))
		{
			return '@exps('.count($exids).')';
		}
		$this->Gateway = 'http://api.sms.cn/mt/';
		$sms = $content;
		if (!ENC_IS_GBK) $sms = ENC_U2G($content);
		if (strlen($phone) >13) $phone = str_replace(';',',',$phone);
		$url  = $this->Gateway;
		$url .= '?';
		$url .= 'uid='.$this->cfg['account'].'&pwd='.md5($this->cfg['password'].$this->cfg['account']).'&mobile='.$phone.'&content='.rawurlencode($sms);
		$this->Debug('Request: Started');
		$this->Debug('Send: '.htmlspecialchars($content));
		$result = $this->Get($url);
		if ($result == '')
		{
			$this->Error('Connected Failed.');
			return $this->result_error('reponse-empty');
		}
		if (!ENC_IS_GBK) $result = ENC_G2U($result);
		$this->Debug('Response: '.htmlspecialchars($result));
		$match = $this->Handle_Respons($result);
		if ($this->IMSend_IS_SUCC($match))
		{
			$this->Debug('Status: Send success.');
		}
		return $this->result_success(
		$this->IMSend_STATUS($match['stat']),
		array(
		'raw'=>serialize($match),
		'status'=>($this->IMSend_IS_SUCC($match) ?'success': 'failed')
		)
		);
	}
	
	public function IMStatus()
	{
		//$url  = $this->Gateway;
		$url .= 'http://api.sms.cn/mm/?';
		$url .= 'uid='.$this->cfg['account'].'&pwd='.md5($this->cfg['password'].$this->cfg['account']);
		$result = $this->Get($url);
		if (!ENC_IS_GBK) $result = ENC_G2U($result);
			$match = $this->Handle_Respons($result);
		if ($match['stat'] == 100)
		{
			$status = '响应正常';
		}
		else
		{
			$status = '响应异常';
		}
		$remain = $match['remain'];
		return sprintf('通道状态：%s<br/>短信剩余：%d 条',$status,$remain);
	}
	
	private function IMSend_IS_SUCC($code)
	{
		if ($code['stat'] == 100) 
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	private function IMSend_STATUS($code)
	{
		$code_STA = array(
		'100'=>'发送成功',
		'101'=>'验证失败',
		'102'=>'短信不足',
		'103'=>'操作失败',
		'104'=>'非法字符',
		'105'=>'内容过多',
		'106'=>'号码过多',
		'107'=>'频率过快',
		'108'=>'号码内容空',
		'109'=>'账号冻结',
		'110'=>'禁止频繁单条发送',
		'112'=>'号码不正确',
		'120'=>'系统升级',
		
		);
		if (isset($code_STA[$code]))
		{	
			return $code_STA[$code];
		}
		else
		{
			return 'ERROR';
		}
	}
	
	private function Handle_Respons($code)
	{
		$result = explode('&',$code);
		$rs     = array();
		foreach ($result as $k =>$v) {
			if ($k==0) {
				continue;
			}
		$rs_kv = explode('=',$v);
		$rs[$rs_kv['0']] = $rs_kv['1'];
	}
		return $rs;
	}
}
?>